import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

export const useAuthStore = defineStore('auth', () => {
  const initializeUsers = () => {
    try {
      return JSON.parse(localStorage.getItem('users')) || [];
    } catch (error) {
      console.error('Failed to parse users from localStorage:', error);
      return [];
    }
  };

  const users = ref(initializeUsers());

  const systemTeacher = {
    name: '系统教师',
    phone: '19999999999',
    password: '12345678',
    role: 'teacher',
    createdAt: new Date().toISOString()
  };

  const systemAdmin = {
    name: '系统管理员',
    phone: '18888888888',
    password: '123456',
    role: 'admin',
    createdAt: new Date().toISOString()
  };

  if (!users.value.some(u => u.phone === systemTeacher.phone && u.role === 'teacher')) {
    users.value.push(systemTeacher);
    localStorage.setItem('users', JSON.stringify(users.value));
  }

  if (!users.value.some(u => u.phone === systemAdmin.phone && u.role === 'admin')) {
    users.value.push(systemAdmin);
    localStorage.setItem('users', JSON.stringify(users.value));
  }

  const rememberMe = ref(JSON.parse(localStorage.getItem('rememberMe')) || false);
  const savedAccount = ref(JSON.parse(localStorage.getItem('savedAccount')) || {});
  const currentUser = ref(null);
  const isAuthenticated = computed(() => !!currentUser.value);

  const persistUsers = () => {
    localStorage.setItem('users', JSON.stringify(users.value));
  };

  const registerUser = (userData) => {
    const phoneRegex = /^1[3-9]\d{9}$/;

    if (!phoneRegex.test(userData.phone)) {
      throw new Error('请输入有效的手机号');
    }

    if (userData.role === 'teacher') {
      throw new Error('禁止注册教师账号');
    }

    if (userData.phone === systemTeacher.phone || userData.phone === systemAdmin.phone) {
      throw new Error('该手机号为系统保留号码');
    }

    if (users.value.some(u => u.phone === userData.phone)) {
      throw new Error('该手机号已注册');
    }

    const newUser = {
      ...userData,
      role: 'student',
      createdAt: new Date().toISOString()
    };

    users.value.push(newUser);
    persistUsers();
  };

  const loginUser = (credentials) => {
    if (credentials.role === 'teacher') {
      const teacher = users.value.find(u =>
        u.phone === systemTeacher.phone &&
        u.role === 'teacher' &&
        u.password === credentials.password
      );

      if (!teacher) {
        throw new Error('教师账号需使用系统指定号码登录');
      }

      currentUser.value = teacher;
      localStorage.setItem('currentUser', JSON.stringify(teacher));
    } else if (credentials.role === 'admin') {
      const admin = users.value.find(u =>
        u.phone === systemAdmin.phone &&
        u.role === 'admin' &&
        u.password === credentials.password
      );

      if (!admin) {
        throw new Error('管理员账号需使用系统指定号码登录');
      }

      currentUser.value = admin;
      localStorage.setItem('currentUser', JSON.stringify(admin));
    } else {
      const user = users.value.find(u =>
        u.phone === credentials.phone &&
        u.password === credentials.password &&
        u.role === credentials.role
      );

      if (!user) {
        throw new Error('账号或密码错误');
      }

      currentUser.value = user;
      localStorage.setItem('currentUser', JSON.stringify(user));
    }

    if (rememberMe.value) {
      savedAccount.value = {
        phone: credentials.phone,
        password: credentials.password
      };
      localStorage.setItem('savedAccount', JSON.stringify(savedAccount.value));
      localStorage.setItem('rememberMe', JSON.stringify(rememberMe.value));
    } else {
      localStorage.removeItem('savedAccount');
      localStorage.removeItem('rememberMe');
      savedAccount.value = {};
      rememberMe.value = false;
    }
  };

  const resetPassword = (phone, newPassword) => {
    const user = users.value.find(u => u.phone === phone);
    if (!user) {
      throw new Error('该手机号未注册');
    }
    user.password = newPassword;
    persistUsers();
  };

  const logout = () => {
    currentUser.value = null;
    localStorage.removeItem('currentUser');
    localStorage.removeItem('savedAccount');
    localStorage.removeItem('rememberMe');
    savedAccount.value = {};
    rememberMe.value = false;
  };

  return {
    users,
    rememberMe,
    savedAccount,
    currentUser,
    isAuthenticated,
    registerUser,
    loginUser,
    resetPassword,
    logout,
    persistUsers
  };
});